import os
import subprocess
import re

class PythonChecker:
    def get_python_versions(self):
        # 获取系统中所有Python版本的路径
        python_versions = {}
        # Windows系统
        if os.name == 'nt':
            try:
                # 获取所有已安装的Python版本
                versions = subprocess.check_output(['py', '--list'], text=True)
                for line in versions.splitlines():
                    if line.strip():
                        # 解析版本号
                        match = re.search(r'-V:(\d+\.\d+).*', line)
                        if match:
                            version = match.group(1)
                            # 获取该版本Python的实际路径
                            try:
                                path = subprocess.check_output(
                                    ['py', f'-{version}', '-c', 'import sys; print(sys.executable)'], 
                                    text=True
                                ).strip()
                                python_versions[version] = path
                            except Exception:
                                continue
            except Exception as e:
                print(f"获取Python版本失败: {e}")
        else:
            # Unix系统（Linux/Mac）
            # 尝试多个可能的Python命令
            python_commands = ['python3.13', 'python3.12', 'python3.11', 'python3.10', 'python3.9', 'python3.8', 'python3.7', 'python3.6', 'python3', 'python']
            for cmd in python_commands:
                try:
                    # 首先检查命令是否存在
                    path = subprocess.check_output(['which', cmd], text=True, stderr=subprocess.DEVNULL).strip()
                    if path:
                        try:
                            # 获取具体版本号
                            ver = subprocess.check_output([path, '--version'], text=True, stderr=subprocess.STDOUT)
                            ver = ver.split()[1].strip()  # 提取版本号
                            python_versions[ver] = path
                        except Exception:
                            continue
                except subprocess.CalledProcessError:
                    continue
                except Exception as e:
                    print(f"获取{cmd}路径失败: {e}")
            
            if not python_versions:
                print("警告: 未找到任何Python版本，请确保系统已安装Python。")
                
        return python_versions 